package com.ctgu.redislock03.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author ALEX
 * @since 2022/10/8 17:23
 */
@Component
public class RedisIdWorker {
    // 开始时间戳，2020-01-01 00:00:00
    private static final long BEGIN_TIMESTAMP = 1577808000L;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public long getNextId(String keyPrefix) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 生成2020-01-01 00:00:00以来的时间戳
        long timeStamp = now.toEpochSecond(ZoneOffset.UTC) - BEGIN_TIMESTAMP;
        // 键为icr:order:2025:03:07，值为当天总销售量计数器
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        String redis_key = "icr:" + keyPrefix + ":" + date;
        long count = redisTemplate.opsForValue().increment(redis_key);
        // 将时间戳左移32位与计数器拼接
        return timeStamp << 32 | count;
    }
}